package com.dmzapp.api.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.xml.Log4jEntityResolver;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dmzapp.api.cache.local.LocalCache;
import com.dmzapp.api.db.AppDao;
import com.dmzapp.api.service.RedisAndDBService;
import com.dmzapp.api.util.Constant;
import com.dmzapp.api.util.PropsUtils;
import com.dmzapp.api.util.StringUtils;
import com.dmzapp.api.vo.UserAccount;

public class ValidateFilter implements Filter {

    Logger logger = LoggerFactory.getLogger("dmzlog");

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    public String getRemortIP(HttpServletRequest request) {

        if (request.getHeader("x-forwarded-for") == null) {

            return request.getRemoteAddr();

        }

        return request.getHeader("x-forwarded-for");

    }

    /**
     * 用于验证用户是否合法，并且包含注册逻辑
     * 
     * 特殊情况：一个用户可以在两台手机上分别用qq和sina登录，这种情况的特殊性在于每个登录授权是一条独立的记录，不能相互登录
     * 
     * 用例详解： 1.
     * 注册：用户第一次安装，微博授权登录，注册操作（判断条件：macaddress和deviceid联合查询没有对应记录，qq或sina授权登录的uid也没有对应记录）
     * 2. 登录授权：用户第二次登录，也是用微博授权，则检查mac地址+deviceid是否与库中匹配，如匹配则验证成功 3.
     * 登录授权：用户第三次登录，换做qq授权登录，此时库中只有微博+mac+deviceid信息，如果qq在全库中不存在，则应该为这条记录加入qq信息，并授权成功
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {

        if(((HttpServletRequest)request).getRequestURI().contains("download_apk") ||
                ((HttpServletRequest)request).getRequestURI().contains("download_count")){
            chain.doFilter(request, response);
            return;
        }
        
        
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String deviceid = request.getParameter("d");
        
        ObjectMapper mapper = new ObjectMapper();
        
        if(StringUtils.isNullOrEmpty(deviceid)){
        	// log & return
        	mapper.writeValue(response.getWriter(), "DeviceID为空");
        	return;
        } 
        
        UserAccount tmp = AppDao.getInstance().getUserByDevice(deviceid);
        if (tmp == null) {
            // 查不到， 注册
            UserAccount registerUser = new UserAccount();
            registerUser.setDeviceid(deviceid);

            boolean s = AppDao.getInstance().insertEnduserR(registerUser);
            if (s) {
                tmp = AppDao.getInstance().getUserByDevice(deviceid);
            } else {
                mapper.writeValue(response.getWriter(), "注册失败");
                return;
            }
        }

        String username = tmp.getUsername();
        
        request.setAttribute("u", username);
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}
